package projet.camping.sevlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import projet.camping.domaine.Habitation;
import projet.camping.exception.ArgumentInvalideException;
import projet.camping.exception.NotYourTurnException;
import projet.camping.exception.PartieNonExistantException;
import projet.camping.usecases.GestionPartie;

@WebServlet(urlPatterns = "/tir.html")
public class GestionTir extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	GestionPartie ucc;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.sendRedirect(resp.encodeRedirectURL("campingBattle.jsp"));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		PrintWriter out = resp.getWriter();
		
		try {
			if(!ucc.isJoueurCourant((String)session.getAttribute("login"), (String)session.getAttribute("nomPartie"))){
				out.write("notIsJoueurCourant");
			}
		} catch (PartieNonExistantException e1) {
			out.write("partieNonExistante");
			System.err.println("la partie n'existe pas");
		} catch (ArgumentInvalideException e) {
			out.write("argument invalide");
		}
		
		int row = Integer.parseInt(req.getParameter("row"));
		int col = Integer.parseInt(req.getParameter("col"));
		Habitation retourTir = null;
		//
		System.out.println("row : " + row + "col " + col);
		try {
			retourTir = ucc.lancerAttaque(
					(String) session.getAttribute("nomPartie"),
					(String) session.getAttribute("login"), col, row);
		} catch (NotYourTurnException e) {
			out.write("notIsJoueurCourant");
		} catch (PartieNonExistantException e) {
			out.write("partieNonExistante");
			System.err.println("la partie n'existe pas");
		} catch (ArgumentInvalideException e) {
			out.write("argument invalide");
		}
		//
		if(retourTir == null){
			out.write("rate");
		}else {
			System.out.println(retourTir.getType().toString());
			out.write(retourTir.getType().toString());
		}
	}
}
